//
//  UITextField+Shake.m
//  HSCategoryKit
//
//  Created by huang on 2018/8/1.
//

#import "UITextField+Shake.h"

static const CGFloat kDefaultTimeCount = 10;
static const CGFloat kDefaultSpeed = 0.04;
static const CGFloat kDefaultDelta = 5;
static const CGFloat kCurrentTimes = 0;

@implementation UITextField (Shake)

- (void)shake
{
    [self shake:kDefaultTimeCount
      withDelta:kDefaultDelta
       andSpeed:kDefaultSpeed
 shakeDirection:ShakeDirectionHorizontal];
}

- (void)shake:(int)times withDelta:(CGFloat)delta
{
	[self shake:times direction:ShakeDirectionVertical currentTimes:kCurrentTimes withDelta:delta andSpeed:kDefaultSpeed shakeDirection:ShakeDirectionHorizontal];
}

- (void)shake:(int)times withDelta:(CGFloat)delta andSpeed:(NSTimeInterval)interval
{
	[self shake:times direction:ShakeDirectionVertical currentTimes:kCurrentTimes withDelta:delta andSpeed:interval shakeDirection:ShakeDirectionHorizontal];
}

- (void)shake:(int)times withDelta:(CGFloat)delta andSpeed:(NSTimeInterval)interval shakeDirection:(ShakeDirection)shakeDirection
{
    [self shake:times direction:ShakeDirectionVertical currentTimes:kCurrentTimes withDelta:delta andSpeed:interval shakeDirection:ShakeDirectionHorizontal];
}

- (void)shake:(int)times direction:(int)direction currentTimes:(int)current withDelta:(CGFloat)delta andSpeed:(NSTimeInterval)interval shakeDirection:(ShakeDirection)shakeDirection
{
	[UIView animateWithDuration:interval animations:^{
		self.transform = (shakeDirection == ShakeDirectionHorizontal) ? CGAffineTransformMakeTranslation(delta * direction, 0) : CGAffineTransformMakeTranslation(0, delta * direction);
	} completion:^(BOOL finished) {
		if(current >= times) {
			self.transform = CGAffineTransformIdentity;
			return;
		}
		[self shake:(times - 1)
		   direction:direction * -1
		currentTimes:current + 1
		   withDelta:delta
			andSpeed:interval
         shakeDirection:shakeDirection];
	}];
}


@end
